package com.jade.bss.base.utils;

import jodd.bean.BeanCopy;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * Explain: 操作Bean公用方法
 * Description:
 *
 * @Author : <a href="mailto:jinghan.lei@basung.com">leijinghan</a>.
 * @Version: 1.0
 * @Date : 16/9/13.
 */
public class CopyBean {

    /**
     * 拷贝Bean 从M对象copy到N对象-全部拷贝
     * @param m 原对象
     * @param clazz 目标类型
     * @return  返回目标对象
     */
    public static <M, N> N copy(M m, Class<N> clazz) throws IllegalAccessException, InstantiationException {
        N n = clazz.newInstance();
        BeanCopy.beans(m, n).declared(true).copy();
        return n;
    }


    public static <M, N> List<N> copy(Collection<M> mList, Class<N> clazz) throws IllegalAccessException, InstantiationException {
        ArrayList<N> nList = new ArrayList<N>();
        for (M m: mList) {
            N n = clazz.newInstance();
            BeanCopy.beans(m, n).declared(true).copy();
            nList.add(n);
        }

        return nList;
    }

    /**
     * 拷贝Bean 从M对象copy到N对象-拷贝指定字段
     * @param m 原对象
     * @param clazz 目标类型
     * @return  返回目标对象
     */
    public static <M, N> N includeCopy(M m, Class<N> clazz, String... fields) throws IllegalAccessException, InstantiationException {
        N n = clazz.newInstance();
        BeanCopy.beans(m, n).include(fields).declared(true).copy();
        return n;
    }


    public static <M, N> List<N> includeCopy(Collection<M> mList, Class<N> clazz, String... fields) throws IllegalAccessException, InstantiationException {
        ArrayList<N> nList = new ArrayList<N>();
        for (M m: mList) {
            N n = clazz.newInstance();
            BeanCopy.beans(m, n).include(fields).declared(true).copy();
            nList.add(n);
        }

        return nList;
    }

    /**
     * 拷贝Bean 从M对象copy到N对象-拷贝非指定字段
     * @param m 原对象
     * @param clazz 目标类型
     * @return  返回目标对象
     */
    public static <M, N> N excludeCopy(M m, Class<N> clazz, String... fields) throws IllegalAccessException, InstantiationException {
        N n = clazz.newInstance();
        BeanCopy.beans(m, n).exclude(fields).declared(true).copy();
        return n;
    }


    public static <M, N> List<N> excludeCopy(Collection<M> mList, Class<N> clazz, String... fields) throws IllegalAccessException, InstantiationException {
        ArrayList<N> nList = new ArrayList<N>();
        for (M m: mList) {
            N n = clazz.newInstance();
            BeanCopy.beans(m, n).exclude(fields).declared(true).copy();
            nList.add(n);
        }

        return nList;
    }
}
